package com.smartcloud.scadmin.core.shiro;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;


public class MyRealm extends AuthorizingRealm {

    /**
     * 权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // TODO Auto-generated method stub
        //获取登录用户的信息,在认证时存储的是ShiroUser 所以得到的就是ShiroUser
        //在其他地方也可通过SecurityUtils.getSubject().getPrincipals()获取用户信息
//        ShiroUser sysUser =  (ShiroUser) principals.getPrimaryPrincipal();
        //权限字符串
        List<String> permissions=new ArrayList<>();
        //从数据库中获取对应权限字符串并存储permissions

        //角色字符串
        List<String> roles=new ArrayList<>();
        //从数据库中获取对应角色字符串并存储roles

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        simpleAuthorizationInfo.addRoles(roles);//角色类型
        return simpleAuthorizationInfo;
    }

    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken arg0) throws AuthenticationException {
        System.out.println("认证=====");
        String userName=((MyAuthenticationToken) arg0).getUsername();
        char[] password=((MyAuthenticationToken) arg0).getPassword();
//        User user=new User();//根据用户名密码获取user，这里不在连接数据库
//        user.setPassword("e10adc3949ba59abbe56e057f20f883e");//123456 md5加密后的值
//        user.setUserName("zyc");//user信息 本该从数据库中获取，这里为了简单，直接模拟
//
//        if(user==null){
//            throw new AuthenticationException("用户名密码错误");
//        }
//        ShiroUser shiroUser=new ShiroUser();//自定义的用户信息类，在shiro中存储使用
//        try {
//            BeanUtils.copyProperties(shiroUser, user);//user信息赋给shiroUser
//        } catch (IllegalAccessException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(shiroUser, user.getPassword(), this.getName());
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
        return simpleAuthenticationInfo;
    }


}